package com.hp.monitoring.pingmon.web.client;

import java.util.Iterator;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.rpc.ServiceDefTarget;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class PingMonWeb implements EntryPoint {

	/**
	 * This is the entry point method.
	 */
	public void onModuleLoad() {
		final Button button = new Button("Check Status now");
		final Label label = new Label();

		final VerticalPanel hostPanel = new VerticalPanel();
		hostPanel.add(button);
		hostPanel.add(label);

		Timer t = new Timer() {
			public void run() {
				label.setText("fetching details");
				MonitorServiceAsync async = (MonitorServiceAsync) GWT
						.create(MonitorService.class);
				ServiceDefTarget endpoint = (ServiceDefTarget) async;
				String moduleRelativeURL = "/pingmon/PingMonServlet";
				endpoint.setServiceEntryPoint(moduleRelativeURL);

				AsyncCallback callback = new AsyncCallback() {
					public void onSuccess(Object result) {
						//    		    for (int i = hostPanel.getWidgetCount(); i > 2; i--)
						//    		    	hostPanel.remove(i);
						Host h = (Host) result;
						Label l = new Label();
						l.setText(h.name);
						hostPanel.add(l);
						Iterator i = h.nodes.iterator();
						while (i.hasNext()) {
							l = new Label();
							Node n = (Node) i.next();
							l.setText(n.name + ": " + n.active);
							hostPanel.add(l);
						}
						label.setText("details retrieved");
					}

					public void onFailure(Throwable caught) {
						label.setText(caught.getMessage());
						caught.printStackTrace();
					}
				};
				async.getPool(callback);
			}
		};

		t.scheduleRepeating(4000);

		button.addClickListener(new ClickListener() {
			public void onClick(Widget sender) {

			}
		});

		// Assume that the host HTML has elements defined whose
		// IDs are "slot1", "slot2".  In a real app, you probably would not want
		// to hard-code IDs.  Instead, you could, for example, search for all 
		// elements with a particular CSS class and replace them with widgets.
		//
		RootPanel.get("slot1").add(hostPanel);

	}
}
